package priv.bestbeat.cloud.user.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import priv.bestbeat.cloud.common.dto.RBACUserDTO;
import priv.bestbeat.cloud.user.entity.PermissionEntity;
import priv.bestbeat.cloud.user.entity.union.RBACUserEntity;
import priv.bestbeat.cloud.user.entity.union.RoleAndPermissionsEntity;
import priv.bestbeat.cloud.user.mapper.IUserMapper;
import priv.bestbeat.cloud.user.service.UserService;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 张渠钦
 * @date 2021/12/9 14:56
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private IUserMapper userMapper;

    @Override
    public RBACUserDTO getRBACUserByUsername(String username) {
        RBACUserEntity entity = userMapper.selectRBACUserByUsername(username);
        if (entity != null) {
            RBACUserDTO rbacUserDTO = new RBACUserDTO();
            BeanUtils.copyProperties(entity,rbacUserDTO);
            Set<String> roles = entity.getRoles().stream().map(RoleAndPermissionsEntity::getCode).collect(Collectors.toSet());
            Set<String> permissions = entity.getRoles().stream().flatMap(role -> role.getPermissions().stream().map(PermissionEntity::getCode)).collect(Collectors.toSet());
            rbacUserDTO.setRoles(roles);
            rbacUserDTO.setPermissions(permissions);
            return rbacUserDTO;
        }
        return null;
    }
}
